import { GlobalData, IFightConfig } from "../../../Script/Common/GlobalData";
import { ITalkData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import BaseSprite from "../../Base/BaseSprite";
import { TalkModule } from "../../Common/TalkModule";
import AudioManager from "../../Util/AudioManager";
import StorageUtil from "../../Util/StorageUtil";
import SliceItem from "./SliceItem";

const { ccclass, property } = cc._decorator;

// const VIEW_DATA: IViewData = {
//     name: 'FightUI',
//     type: EViewType.Panel,
//     bundle: EBundleType.Game,
//     zIndex: 100,
// };

/** 互怼小玩法 */
@ccclass
export default class FightUI extends BaseSprite {
    public static instance: FightUI = null;

    @property({ type: cc.Node, tooltip: "root节点" })
    private rootNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "pk节点" })
    private pkNode: cc.Node = null;

    @property({ type: cc.Node, tooltip: "气泡父节点" })
    private bubbles: cc.Node = null;
    @property({ type: [cc.Node], tooltip: "生命值(心)节点" })
    private hps: cc.Node[] = [];
    @property({ type: cc.Node, tooltip: "npc对话框" })
    private npcTalk: cc.Node = null;
    @property({ type: cc.Node, tooltip: "玩家对话框" })
    private playerTalk: cc.Node = null;

    @property({ type: cc.Node, tooltip: "互怼光" })
    private clicklight: cc.Node = null;
    @property({ type: cc.Node, tooltip: "开怼按钮" })
    private btnFight: cc.Node = null;
    @property({ type: cc.Node, tooltip: "头像" })
    private fire: cc.Node = null;
    @property({ type: cc.ProgressBar, tooltip: "进度条" })
    private progress: cc.ProgressBar = null;
    @property({ type: cc.Label, tooltip: "进度条文本" })
    private labProgress: cc.Label = null;

    @property({ type: sp.Skeleton, tooltip: "pk动画" })
    private pkSke: sp.Skeleton = null;
    @property({ type: sp.Skeleton, tooltip: "滑动提示动画" })
    public huaTipSke: sp.Skeleton = null;
    @property({ type: sp.Skeleton, tooltip: "爆炸动画" })
    private boomSke: sp.Skeleton = null;
    @property({ type: cc.Node, tooltip: "子弹节点" })
    private bullet: cc.Node = null;

    private curHp: number = 4;
    private curCount: number = 0;
    private config: IFightConfig = null;

    private talkData: ITalkData = null;

    protected onLoad() {
        super.onLoad();

        // // 隐藏顶部资源框
        // Message.instance.send(EventID.HIDE_VIEW_CLOSE, { hide: 'top' });

        FightUI.instance = this;

        this.talkData = StorageUtil.instance.getTalkData();

        this.init();
    }

    protected onEnable() {
        // this.schedule(this.showOneBubble, 1);
    }
    protected onDisable() {
        this.unschedule(this.showOneBubble);
    }

    private isFirst: boolean = true;
    public showHuaTip() {
        if (this.isFirst) {
            this.isFirst = false;
            this.huaTipSke.node.active = true;
        }
    }

    public hideHuaTip() {
        this.huaTipSke.node.active = false;
    }

    private init() {
        this.rootNode.active = false;
        this.pkNode.active = true;

        // pk动画
        AudioManager.instance.playSound("电流PK");
        this.pkSke.node.active = true;
        this.pkSke.setAnimation(0, 'animation', false);
        this.pkSke.setCompleteListener((trackEntry, loopCount) => {
            if (trackEntry.animation.name === 'animation') {
                this.pkSke.node.active = false;

                // 初始化
                this.rootNode.active = true;
                this.pkNode.active = false;
                this.curHp = this.hps.length;
                this.initData();
                this.refreshUI();
            }
        });
    }

    private initData() {
        this.config = GlobalData.getFightConfig(this.hps.length - this.curHp + 1);
        this.curCount = 0;

        this.isClicked = false;
        this.npcTalk.active = true;
        this.playerTalk.active = false;
        this.btnFight.active = false;
        this.fire.active = true;
        this.progress.node.active = true;

        AudioManager.instance.playSound(this.config.shoper);
        const labNpcTalk = cc.find('lab', this.npcTalk).getComponent(cc.Label);
        GameUtil.effectWords(labNpcTalk, this.config.shoper, async () => {
            await GameUtil.sleep(500);
            this.npcTalk.active = false;
            this.schedule(this.showOneBubble, 1);
            this.showHuaTip();
        });
    }

    private refreshUI() {
        // 刷新进度条
        const data = this.getFightEnd();
        this.progress.progress = data.cur / data.max;
        this.labProgress.string = `${data.cur}/${data.max}`;
        this.progress.node.active = !this.playerTalk.active;
        // 刷新npc血量
        for (let i = 0; i < this.hps.length; i++) {
            const xin = cc.find("xin", this.hps[i]);
            xin.active = i < this.curHp;
        }

        if (data.cur >= data.max) {
            // this.playerTalk.active = true;
            this.btnFight.active = true;
            this.fire.active = false;
            this.progress.node.active = false;
        }
    }

    private showOneBubble() {
        this.refreshUI();

        const data = this.getFightEnd();
        if (data.isEnd) {
            // console.log("完成完成~~~~");
            return;
        }

        const item = this.getUnuseItem();
        if (item) {
            AudioManager.instance.playSound("气泡出现音效");
            // 随机文本内容
            const strArr = this.config.bubble.split("/");
            const index = Math.floor(Math.random() * strArr.length);
            // 设置位置、静态、边框
            item.angle = 0;
            item.scale = 0;
            item.active = true;
            item.getComponent(SliceItem).draw(strArr[index]);
            const body = item.getComponent(cc.RigidBody);
            const collider = item.getComponent(cc.PhysicsPolygonCollider);
            body.type = cc.RigidBodyType.Static;
            body.active = false;
            collider.points = [
                cc.v2(-item.width / 2, -item.height / 2),
                cc.v2(-item.width / 2, item.height / 2),
                cc.v2(item.width / 2, item.height / 2),
                cc.v2(item.width / 2, -item.height / 2),
            ];
            // 气泡弹出动画
            item.stopAllActions();
            cc.tween(item).sequence(
                cc.moveTo(0, cc.v2(Math.random() * 400 - 200, Math.random() * 500 - 250)),
                cc.scaleTo(0, 0),
                cc.scaleTo(0.3, 1),
            ).start();
            // 设置气泡计数
            this.curCount++;
        }
    }

    private count: number = 0;
    private fireBullet() {
        if (this.count >= 10) {
            this.nextFight();
            return;
        }

        this.count++;
        const self = this;
        const config = GlobalData.getFightRandom();
        const bullet = cc.instantiate(this.bullet);
        bullet.active = true;
        bullet.parent = this.bullet.parent;
        bullet.angle = config.angle;
        bullet.setPosition(config.start);
        cc.tween(bullet).sequence(
            cc.moveTo(0.15, config.end),
            cc.callFunc(() => {
                bullet.destroy();
                this.fireBullet();
                GameUtil.vibration(self.node);
                const x = GameUtil.getRandomInteger(self.boomSke.node.x - 50, self.boomSke.node.x + 50);
                const y = GameUtil.getRandomInteger(self.boomSke.node.y - 50, self.boomSke.node.y + 50);
                const boom = cc.instantiate(self.boomSke.node);
                boom.active = true;
                boom.parent = self.boomSke.node.parent;
                boom.setPosition(cc.v2(x, y));
                GameUtil.playAnimation({
                    ske: boom.getComponent(sp.Skeleton), animName: 'baozha', isLoop: false, callback: () => {
                        boom.destroy();
                    }
                });
            }),
        ).start();
    }

    private async nextFight() {
        this.playerTalk.active = false;
        this.curHp--;
        if (this.curHp > 0) {
            this.initData();
            this.refreshUI();
        } else {
            this.npcTalk.active = true;

            // SceneGame.instance.removeAllPopView();
            this.onClose();
            this.talkData.id = 11105;
            TalkModule.updateCheck();
        }
    }

    private getUnuseItem() {
        for (let i = 0; i < this.bubbles.children.length; i++) {
            const item = this.bubbles.children[i];
            if (!item.active) {
                return item;
            }
        }
        return null;
    }

    private getFightEnd() {
        const showCount = this.getShowItemCount();
        const cur = this.curCount - showCount;
        const max = this.config.max;
        return { isEnd: cur >= max, cur: Math.min(cur, max), max };
    }

    private getShowItemCount() {
        let count = 0;
        for (let i = 0; i < this.bubbles.children.length; i++) {
            const item = this.bubbles.children[i];
            if (item.active) {
                count++;
            }
        }
        return count;
    }

    private createLight() {
        const node = cc.instantiate(this.clicklight);
        node.parent = this.clicklight.parent;
        node.active = true;
        cc.tween(node).sequence(
            cc.scaleTo(0, 0.9, 0.9),
            cc.scaleTo(0.3, 1, 1),
            cc.callFunc(() => {
                node.destroy();
            }),
        ).start();
    }

    private onClose() {
        this.node.destroy();
        SceneGame.instance.removeAllPopView();
    }

    private isClicked: boolean = false;
    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case "btnFight":
                {
                    this.createLight();

                    const data = this.getFightEnd();
                    if (!data.isEnd) {
                        return;
                    }

                    if (this.isClicked) {
                        return;
                    }
                    this.isClicked = true;

                    AudioManager.instance.playSound(this.config.player);
                    const labPlayerTalk = cc.find('lab', this.playerTalk).getComponent(cc.Label);
                    this.playerTalk.active = true;
                    this.progress.node.active = false;
                    GameUtil.effectWords(labPlayerTalk, this.config.player, async () => {
                        AudioManager.instance.playSound("突突突");
                        this.count = 0;
                        this.fireBullet();
                    });
                }
                break;
            case "btnClose":
                {
                    this.onClose();
                }
                break;
        }
    }
}
// AppService.instance.registViewData(VIEW_DATA);